<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    :footer="false"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div style="display: flex;gap:20px;margin-bottom: 20px">
      <a-button type="primary" @click="handleGenerateRequest">生成请购单</a-button>
      <span style="line-height: 32px">选择仓库：</span>
      <j-multi-select-tag
        dict-code="hf_warehouse,warehouse_name,id"
        v-model="warehouses"
        style="width: 50%"
      ></j-multi-select-tag>
      <a-button @click="loadData">加载数据</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDelete">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <a-button
        v-if="!editable"
        type="primary"
        @click="handleEditNumber"
        style="margin-bottom: 20px;position: absolute;right: 30px"
        >编辑
      </a-button>
      <a-button
        v-else
        type="primary"
        @click="handleSaveNumber"
        style="margin-bottom: 20px;position: absolute;right: 30px"
        >保存
      </a-button>
    </div>

    <a-table
      ref="table"
      size="small"
      bordered
      rowKey="materialCode"
      class="j-table-force-nowrap"
      :scroll="{ x: true }"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :customRow="clickThenSelect"
      @change="handleTableChange"
    >
      <template slot="purchaseNumber" slot-scope="text, record">
        <a-input-number v-if="editable" v-model="record['purchaseNumber']" :min="0" style="" />
        <span v-else>{{ record['purchaseNumber'] }}</span>
      </template>
    </a-table>
  </j-modal>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction } from '@api/manage'

export default {
  name: 'MRPModal',
  mixins: [JeecgListMixin],
  props: {
    saleOrderIds: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: 'MRP运算',
      width: 1200,
      visible: false,
      queryParam: {},
      warehouses: '1644242858342989825,1644242906934001666,1777570942979661825,1777570899157573633',
      editable: false,
      model: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      disableMixinCreated: true,
      /* 排序参数 */
      isorter: {
        column: 'materialCode',
        order: 'desc'
      },
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* table加载状态 */
      loading: false,
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber'
        },
        {
          title: '预测需求量',
          align: 'center',
          dataIndex: 'requireNumber'
        },
        {
          title: '库存',
          align: 'center',
          dataIndex: 'storageNumber'
        },
        {
          title: '需要采购数量',
          align: 'center',
          dataIndex: 'purchaseNumber',
          scopedSlots: { customRender: 'purchaseNumber' }
        }
      ],
      confirmLoading: false,
      validatorRules: {},
      url: {
        generateRequest: '/purchase/hfPurchaseRequest/generateByMRP',
        list: 'sale/hfSaleOrder/mrpList'
      }
    }
  },
  methods: {
    loadData() {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      this.loading = true
      getAction(this.url.list, {
        saleOrderIds: this.saleOrderIds,
        warehouses: this.warehouses
      })
        .then(res => {
          if (res.success) {
            this.dataSource = res.result
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.onSelectChange(record.materialCode.split(','), [record])
          }
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.clearList()
    },
    handleCancel() {
      this.close()
    },
    handleGenerateRequest() {
      if (this.dataSource.length === 0) {
        this.$message.info('目前库存充足，无需进行采购')
        return
      }
      postAction(this.url.generateRequest, {
        hfPurchaseRequestDetails: this.dataSource
          .map(item => ({
            ...item,
            number: item.purchaseNumber
          }))
          .filter(item => item.purchaseNumber > 0),
        saleOrderId: this.saleOrderIds
      }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    batchDelete() {
      // 将数据从datasource中删除
      let temp = this.dataSource.filter(item => !this.selectedRowKeys.includes(item.materialCode))
      this.dataSource = Object.assign([], temp)
    },
    handleEditNumber() {
      this.editable = true
    },
    handleSaveNumber() {
      this.editable = false
      this.$message.success('保存成功')
    }
  }
}
</script>

<style scoped></style>
